<?php

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Hash;
use Tymon\JWTAuth\Facades\JWTAuth;
use Validator;

class FileUploadController extends Controller
{


   public function uploadImg(Request $request){
        if ($request->hasFile('file')){
            $file = $request->file('file');
            if ($file->isValid()) {
                 // 获取文件相关信息
                $originalName = $file->getClientOriginalName(); // 文件原名
                $ext = $file->getClientOriginalExtension();     // 扩展名
                $realPath = $file->getRealPath();   //临时文件的绝对路径
                $type = $file->getClientMimeType();     // image/jpeg
                // // 上传文件
                
                if ($ext === false) {
                    return response()->json(['code' => -1,'msg' => '无效的图片文件','data' => null]);
                }
                if (!in_array($ext, ['jpg', 'jpeg', 'png'])) {
                    return response()->json(['code' => -1,'msg' => '无效的图片格式','data' => null]);
                }

                $target_path = 'upload/' . date('Y/m/d/');
                $filename = date('YmdHis') . '-' . uniqid() . '.' . $ext;
                $targetPath = public_path() . DIRECTORY_SEPARATOR . $target_path;
                if (!is_dir($targetPath)) {
                    if (!mkdir($targetPath, 0777, 1)) {
                        return response()->json(['code' => -1,'msg' => '无法建立上传目录','data' => null]);
                    }
                }
                if($file->move($target_path,$filename)){
                    $url = config('services.domain');
                    return response()->json(['code' => 1,'msg' => 'Success','data' => $url.$target_path.$filename]);
                }else{
                    return response()->json(['code' => -1,'msg' => '上传失败','data' => null]);
                }
            }else{
                return response()->json(['code' => -1,'msg' => '上传失败','data' => null]);
            }
        }
        return response()->json(['code' => -1,'msg' => '无文件上传','data' => null]);
    }

}
